<?php
namespace App\Common\Lib;

use App\Common as com;

class Db extends com\Lib\LibBase {

	/**
	 * 执行事务过程
	 * @param \Closure $fn
	 * @return mixed
	 * @throws \Throwable
	 */
	public static function transaction( \Closure $fn ):mixed {
		\Hyperf\DbConnection\Db::beginTransaction();
		try {
			$res = call_user_func( $fn );
			//
			\Hyperf\DbConnection\Db::commit();
			//
			return $res;
		}catch( \Exception $e ){
			\Hyperf\DbConnection\Db::rollBack();
			com\Lib\Err\Exception\Try_::dealWithException( $e, true );
		}
	}

	/**
	 * 执行事务过程
	 * @param \Closure $fn
	 * @return mixed
	 * @throws \Throwable
	 */
	public static function transactionCheckFalse( \Closure $fn ):mixed {
		\Hyperf\DbConnection\Db::beginTransaction();
		try {
			$res = call_user_func( $fn );
			if( $res === false ){
				\Hyperf\DbConnection\Db::rollBack();
				//
				return false;
			}
			//
			\Hyperf\DbConnection\Db::commit();
			//
			return $res;
		}catch( \Exception $e ){
			\Hyperf\DbConnection\Db::rollBack();
			com\Lib\Err\Exception\Try_::dealWithException( $e, true );
		}
	}

}
